#!/usr/bin/env bash

# 输入 ctrl + C 将退出整个shell
trap "exit" INT

# 提前获取 sudo 权限
sudo -v

while [ 1 ]
do
  # 运行模式( production | development )
  echo -e "Please select your environment. ( prod | production | dev | development )"
  echo -n "Your choise (default:production): "
  read ENV_MODE

  if  [ ! -n "$ENV_MODE" ] ;then
    ENV_MODE=production
    break
  fi

  case "$(echo ${ENV_MODE} | tr '[A-Z]' '[a-z]')" in
    "prod" | "production")
      ENV_MODE=production
      break
      ;;
    "dev" | "development")
      ENV_MODE=development
      break
      ;;
    *)
      echo -e "\033[1;44;37mINFO\033[0m: WRONG SELECTION: ${ENV_MODE}"
      ;;
    esac
done


while [ 1 ]
do
  #是否安装测试数据(on:是，off:否)
  echo -n "Insert damo data? (YES/NO, default:NO): "
  read SITE_DEMO

  if  [ ! -n "$SITE_DEMO" ] ;then
    SITE_DEMO=off
    break
  fi

  case "$(echo ${SITE_DEMO} | tr '[A-Z]' '[a-z]')" in
    "y" | "yes")
      SITE_DEMO=on
      break
      ;;
    "n" | "no")
      SITE_DEMO=on
      break
      ;;
    *)
      echo -e "\033[1;44;37mINFO\033[0m: WRONG SELECTION: ${SITE_DEMO}"
      ;;
    esac
done

while [ 1 ]
do
  #站点域名(不包括http)
  echo -n "Wesite URL (without http): "
  read SITE_DOMAIN

  if  [ ! -n "$SITE_DOMAIN" ] ;then
    echo -e "\033[1;44;37mINFO\033[0m: WESITE URL CAN NOT BE EMPTY!"
  else
    break
  fi
done

while [ 1 ]
do
  #站点密钥(数字字母组合，不要用特殊字符)
  echo -n "Site key (example: 1qaz2wsx3edc): "
  read SITE_KEY

  if  [ ! -n "$SITE_KEY" ] ;then
    echo -e "\033[1;44;37mINFO\033[0m: SITE KEY CAN NOT BE EMPTY!"
  else
    break
  fi
done

while [ 1 ]
do
  #mysql超级用户密码（数字字母组合，不要用特殊字符）
  echo -n "MySql root password (example: 1qaz2wsx3edc): "
  read MYSQL_ROOT_PASSWORD

  if  [ ! -n "$MYSQL_ROOT_PASSWORD" ] ;then
    echo -e "\033[1;44;37mINFO\033[0m: PASSWORD CAN NOT BE EMPTY!"
  else
    break
  fi
done

#mysql主机名称（非独立实例请不要修改，独立实例填写主机IP）
MYSQL_HOST=mysql

#mysql主机端口（非独立实例请不要修改）
MYSQL_PORT=3306

while [ 1 ]
do
  #mysql项目数据库名称（数字字母组合，不要用特殊字符）
  echo -n "MySql database: "
  read MYSQL_DATABASE

  if  [ ! -n "$MYSQL_DATABASE" ] ;then
    echo -e "\033[1;44;37mINFO\033[0m: MYSQL DATABASE CAN NOT BE EMPTY!"
  else
    break
  fi
done

while [ 1 ]
do
  #mysql项目数据库用户（数字字母组合，不要用特殊字符）
  echo -n "MySql user: "
  read MYSQL_USER

  if  [ ! -n "$MYSQL_USER" ] ;then
    echo -e "\033[1;44;37mINFO\033[0m: MYSQL USER CAN NOT BE EMPTY!"
  else
    break
  fi
done

while [ 1 ]
do
  #mysql项目数据库密码（数字字母组合，不要用特殊字符）
  echo -n "MySql user password (example: 1qaz2wsx3edc): "
  read MYSQL_PASSWORD

  if  [ ! -n "$MYSQL_PASSWORD" ] ;then
    echo -e "\033[1;44;37mINFO\033[0m: PASSWORD CAN NOT BE EMPTY!"
  else
    break
  fi
done


#redis主机名称（非独立实例请不要修改，独立实例填写主机IP）
REDIS_HOST=redis

while [ 1 ]
do
  #redis访问密码（数字字母组合，不要用特殊字符）
  echo -n "Redis password (example: 1qaz2wsx3edc): "
  read REDIS_PASSWORD

  if  [ ! -n "$REDIS_PASSWORD" ] ;then
    echo -e "\033[1;44;37mINFO\033[0m: PASSWORD CAN NOT BE EMPTY!"
  else
    break
  fi
done

# ------------ @@@ 以下内容，非专业人士请勿修改，新手请远离！ @@@ ------------- #

# 项目目录
PROJECT_DIR=$PWD

# Docker目录
DOCKER_DIR=${PROJECT_DIR}/docker

# 容器内部路径
CTN_PROJECT_DIR=/www

#成功信息输出
success_print() {
  echo -e "\033[32m $1 \033[0m"
}

#失败信息输出
error_print() {
  echo -e "\033[31m $1 \033[0m"
}

#系统判断
os_type() {
  os=$(grep "^ID=" /etc/os-release)
  if [[ ${os} =~ 'centos' ]]; then
    echo 'centos'
  elif [[ ${os} =~ 'ubuntu' ]]; then
    echo 'ubuntu'
  elif [[ ${os} =~ 'debian' ]]; then
    echo 'debian'
  else
    echo 'other'
  fi
}

#安装git和curl
if [ "$(os_type)" = 'ubuntu' ] || [ "$(os_type)" = 'debian' ]; then
  sudo apt-get update && sudo apt-get install -y curl git
elif [ "$(os_type)" = 'centos' ]; then
  sudo yum update && sudo yum install -y curl git
else
  error_print "\n------ sorry, we only support ubuntu, debian, centos currently. ------\n"
  exit
fi

# docker .env文件
DOCKER_ENV=${DOCKER_DIR}/.env

#复制环境变量文件
cp "${DOCKER_DIR}/.env.default" "${DOCKER_ENV}"

#替换docker .env配置项
sed -i "s/ENV_MODE.*/ENV_MODE=${ENV_MODE}/g" "${DOCKER_ENV}"
sed -i "s:CTN_PROJECT_DIR.*:CTN_PROJECT_DIR=${CTN_PROJECT_DIR}:g" "${DOCKER_ENV}"
sed -i "s/MYSQL_ROOT_PASSWORD.*/MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}/g" "${DOCKER_ENV}"
sed -i "s/MYSQL_DATABASE.*/MYSQL_DATABASE=${MYSQL_DATABASE}/g" "${DOCKER_ENV}"
sed -i "s/MYSQL_USER.*/MYSQL_USER=${MYSQL_USER}/g" "${DOCKER_ENV}"
sed -i "s/MYSQL_PASSWORD.*/MYSQL_PASSWORD=${MYSQL_PASSWORD}/g" "${DOCKER_ENV}"
sed -i "s/REDIS_PASSWORD.*/REDIS_PASSWORD=${REDIS_PASSWORD}/g" "${DOCKER_ENV}"

#nginx配置目录
NGINX_CONF_DIR=${DOCKER_DIR}/nginx/conf.d
NGINX_SITE_CONF=${NGINX_CONF_DIR}/default.conf

#复制nginx站点配置文件
cp "${NGINX_CONF_DIR}/default.conf.sample" "${NGINX_SITE_CONF}"

#替换nginx　default.conf配置项
sed -i "s/server_name .*/server_name ${SITE_DOMAIN};/g" "${NGINX_SITE_CONF}"
sed -i "s:root .*:root ${CTN_PROJECT_DIR}/public;:g" "${NGINX_SITE_CONF}"

# 项目 config目录
PROJECT_CONF_DIR=${PROJECT_DIR}/config
PROJECT_CONF_FILE=${PROJECT_CONF_DIR}/config.php

#复制config.php
cp "${PROJECT_CONF_DIR}/config.default.php" "${PROJECT_CONF_FILE}"

#替换config.php配置项
sed -i "s/\$config\['key'\].*/\$config['key'] = '${SITE_KEY}';/g" "${PROJECT_CONF_FILE}"
sed -i "s/\$config\['db'\]\['host'\].*/\$config['db']['host'] = '${MYSQL_HOST}';/g" "${PROJECT_CONF_FILE}"
sed -i "s/\$config\['db'\]\['port'\].*/\$config['db']['port'] = '${MYSQL_PORT}';/g" "${PROJECT_CONF_FILE}"
sed -i "s/\$config\['db'\]\['dbname'\].*/\$config['db']['dbname'] = '${MYSQL_DATABASE}';/g" "${PROJECT_CONF_FILE}"
sed -i "s/\$config\['db'\]\['username'\].*/\$config['db']['username'] = '${MYSQL_USER}';/g" "${PROJECT_CONF_FILE}"
sed -i "s/\$config\['db'\]\['password'\].*/\$config['db']['password'] = '${MYSQL_PASSWORD}';/g" "${PROJECT_CONF_FILE}"
sed -i "s/\$config\['redis'\]\['host'\].*/\$config['redis']['host'] = '${REDIS_HOST}';/g" "${PROJECT_CONF_FILE}"
sed -i "s/\$config\['redis'\]\['auth'\].*/\$config['redis']['auth'] = '${REDIS_PASSWORD}';/g" "${PROJECT_CONF_FILE}"
sed -i "s/\$config\['websocket'\]\['connect_address'\].*/\$config['websocket']['connect_address'] = 'http:\/\/${SITE_DOMAIN}:8282';/g" "${PROJECT_CONF_FILE}"

#复制xunsearch配置文件
cp "${PROJECT_CONF_DIR}/xs.course.default.ini" "${PROJECT_CONF_DIR}/xs.course.ini"
cp "${PROJECT_CONF_DIR}/xs.article.default.ini" "${PROJECT_CONF_DIR}/xs.article.ini"
cp "${PROJECT_CONF_DIR}/xs.question.default.ini" "${PROJECT_CONF_DIR}/xs.question.ini"
cp "${PROJECT_CONF_DIR}/xs.group.default.ini" "${PROJECT_CONF_DIR}/xs.group.ini"
cp "${PROJECT_CONF_DIR}/xs.user.default.ini" "${PROJECT_CONF_DIR}/xs.user.ini"

#安装docker
if [ -z "$(command -v docker)" ]; then
  sudo curl -sSL https://get.daocloud.io/docker | sh
  sudo systemctl enable docker
fi

if [ -z "$(command -v docker)" ]; then
  error_print "\n------ error: docker command not found, please try again. ------\n"
  exit
fi

if [ ! -d '/etc/docker' ]; then
  sudo mkdir -p '/etc/docker'
fi

#docker镜像加速
if [ ! -e '/etc/docker/daemon.json' ]; then
  echo '{"registry-mirrors": ["https://mirror.ccs.tencentyun.com"]}' | sudo tee /etc/docker/daemon.json
  sudo systemctl daemon-reload
  sudo systemctl restart docker
  sudo chmod 666 /var/run/docker.sock
fi

#安装docker-composer
if [ -z "$(command -v docker-compose)" ]; then
  sudo curl -L "https://get.daocloud.io/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
  sudo chmod +x /usr/local/bin/docker-compose
fi

if [ -z "$(command -v docker-compose)" ]; then
  error_print "\n------ error: docker-compose command not found, please try again. ------\n"
  exit
fi

#切换到基准目录
cd "${DOCKER_DIR}" || exit

#构建镜像
sudo docker-compose build

#启动容器
docker-compose down && docker-compose up -d

CTN_TMP_SITEMAP_XML=${CTN_PROJECT_DIR}/storage/tmp/sitemap.xml
CTN_PUBLIC_SITEMAP_XML=${CTN_PROJECT_DIR}/public/sitemap.xml

docker exec -i ve-php bash <<EOF

#创建并连接sitemap.xml
if [ ! -e ${CTN_TMP_SITEMAP_XML} ]; then
  touch ${CTN_TMP_SITEMAP_XML}
fi

ln -sf ${CTN_TMP_SITEMAP_XML} ${CTN_PUBLIC_SITEMAP_XML}

#修改storage目录权限
#chown -R www-data:www-data ${CTN_PROJECT_DIR}/storage ${CTN_PROJECT_DIR}/public

exit
EOF

docker exec -i --user www-data:www-data ve-php bash <<EOF

#切换到项目目录
cd ${CTN_PROJECT_DIR}

#安装依赖包
if [ "$ENV_MODE" = "production" ] ; then
  composer install --no-dev
  composer dump-autoload --optimize
else
  composer install
  composer dump-autoload --optimize
fi

until nc -z -v -w30 mysql 3306 &> /dev/null
do
  echo "Waiting for database connection..."
  sleep 1
done

#数据迁移
vendor/bin/phinx migrate

# 安装演示数据
if [ "$SITE_DEMO" = "on" ] ; then
  vendor/bin/phinx seed:run
fi

#程序升级
php console.php upgrade

#重建xunsearch索引
php console.php course_index rebuild
php console.php article_index rebuild
php console.php question_index rebuild
php console.php group_index rebuild
php console.php user_index rebuild

#清理log（之前步骤以root身份产生日志会让www-data用户无写入权限）
rm -f storage/log/*.log

exit
EOF

#重启php容器（websocket依赖WorkerGateway相关包，之前启动php容器时并未安装相关包）
docker container restart ve-php

docker_ps=$(docker ps)

if [[ "${docker_ps}" =~ 'nginx' ]]; then
  success_print "nginx service ok\n"
else
  error_print "nginx service failed\n"
fi

if [[ "${docker_ps}" =~ 'php' ]]; then
  success_print "php service ok\n"
else
  error_print "php service failed\n"
fi

if [[ "${docker_ps}" =~ 'mysql' ]]; then
  success_print "mysql service ok\n"
else
  error_print "mysql service failed\n"
fi

if [[ "${docker_ps}" =~ 'redis' ]]; then
  success_print "redis service ok\n"
else
  error_print "redis service failed\n"
fi

if [[ "${docker_ps}" =~ 'xunsearch' ]]; then
  success_print "xunsearch service ok\n"
else
  error_print "xunsearch service failed\n"
fi

cat > "${PROJECT_DIR}/install_success.info" <<EOF
ENV_MODE=${ENV_MODE}
SITE_DEMO=${SITE_DEMO}
SITE_DOMAIN=${SITE_DOMAIN}
SITE_KEY=${SITE_KEY}
MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
MYSQL_HOST=${MYSQL_HOST}
MYSQL_PORT=${MYSQL_PORT}
MYSQL_DATABASE=${MYSQL_DATABASE}
MYSQL_USER=${MYSQL_USER}
MYSQL_PASSWORD=${MYSQL_PASSWORD}
REDIS_HOST=${REDIS_HOST}
REDIS_PASSWORD=${REDIS_PASSWORD}
EOF

echo -e "\n\n==========================================================================================="
echo -e "===================================== Success Install ====================================="
echo -e "==========================================================================================="
echo -e "ENV_MODE=${ENV_MODE}"
echo -e "SITE_DEMO=${SITE_DEMO}"
echo -e "SITE_DOMAIN=${SITE_DOMAIN}"
echo -e "SITE_KEY=${SITE_KEY}"
echo -e "MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}"
echo -e "MYSQL_HOST=${MYSQL_HOST}"
echo -e "MYSQL_PORT=${MYSQL_PORT}"
echo -e "MYSQL_DATABASE=${MYSQL_DATABASE}"
echo -e "MYSQL_USER=${MYSQL_USER}"
echo -e "MYSQL_PASSWORD=${MYSQL_PASSWORD}"
echo -e "REDIS_HOST=${REDIS_HOST}"
echo -e "REDIS_PASSWORD=${REDIS_PASSWORD}"
echo -e "===========================================================================================\n\n"

echo -e "\033[1;44;37mINFO\033[0m: You could use ./ve [command] to do something\n\n"
